package com.myapi.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.myapi.client.PlayerHandDAO;
import com.myapi.client.DAO.CardDAO;
import com.myapi.client.DAO.PlayerDAO;
import com.myapi.client.DAO.StatisticDAO;
import com.myapi.client.DAO.TableDAO;

public class BDD {
	ArrayList<PlayerDAO> player; 
	public static void saveTableInfo(TableDAO tableDAO){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		cleanBDD();
		try {
			pm.makePersistent(tableDAO);
			for(PlayerHandDAO play:tableDAO.getPlayerHands()){
			
		//			pm.makePersistent(play);
			}
		} finally {
			pm.close();
		}
	}
	public static void cleanBDD(){
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + TableDAO.class.getName();
			List greetings = (List<TableDAO>) pm.newQuery(query).execute();
			//pm.deletePersistentAll(greetings);
			query = "select from " + CardDAO.class.getName();
			greetings = (List<TableDAO>) pm.newQuery(query).execute();
			//pm.deletePersistentAll(greetings);
			query = "select from " + PlayerHandDAO.class.getName();
			greetings = (List<TableDAO>) pm.newQuery(query).execute();
			//pm.deletePersistentAll(greetings);
			query = "select from " + PlayerDAO.class.getName();
			greetings = (List<TableDAO>) pm.newQuery(query).execute();
			//pm.deletePersistentAll(greetings);
		} finally {
			pm.close();
		}
		
	}
	
	public static ArrayList<PlayerHandDAO> getListPlayerHandInfo(PlayerDAO player) {
		ArrayList<PlayerHandDAO> playerHandDAO=new ArrayList<PlayerHandDAO>();
		//cleanBDD();
		PersistenceManager pme = PMF.get().getPersistenceManager();
		try {
		String query = "select from " + TableDAO.class.getName();
		List<TableDAO> greetings = (List<TableDAO>) pme.newQuery(query).execute();
		if (greetings.isEmpty()) 
			System.out.println("No Table in Database");
		else
		{
			TableDAO tableDAO = greetings.get(greetings.size()-1);

				String cards="";
				query = "select from " + PlayerHandDAO.class.getName();
				List<PlayerHandDAO> greetigs = (List<PlayerHandDAO>) pme.newQuery(query).execute();
				
				for(PlayerHandDAO playerhand : tableDAO.getPlayerHands()){
					if(player.getId().equals(playerhand.getPlayerInfo().getId())){
						PokerServiceImpl p=PokerServiceImpl.getpokerServerControler();
						p.addMessage(playerhand.getCards().get(0).getSuit()+playerhand.getCards().get(0).getValue());
						playerHandDAO.add(playerhand.copy());

					}
				}
			}

		
	} finally {
		pme.close();
	}
		return playerHandDAO;

	}
}
